import Cookies from 'js-cookie'

const TOKEN_KEY = 'wzh_token'
const TOKEN_EXPIRE_KEY = 'wzh_token_expire'

/**
 * 获取token
 */
export function getToken(): string | undefined {
  return Cookies.get(TOKEN_KEY)
}

/**
 * 设置token
 * @param token token值
 * @param expires 过期时间（天数），默认7天
 */
export function setToken(token: string, expires: number = 7): void {
  Cookies.set(TOKEN_KEY, token, { expires })
  
  // 设置过期时间戳
  const expireTime = new Date().getTime() + expires * 24 * 60 * 60 * 1000
  Cookies.set(TOKEN_EXPIRE_KEY, expireTime.toString(), { expires })
}

/**
 * 移除token
 */
export function removeToken(): void {
  Cookies.remove(TOKEN_KEY)
  Cookies.remove(TOKEN_EXPIRE_KEY)
}

/**
 * 检查token是否过期
 */
export function isTokenExpired(): boolean {
  const expireTime = Cookies.get(TOKEN_EXPIRE_KEY)
  if (!expireTime) {
    return true
  }
  
  const now = new Date().getTime()
  return now > parseInt(expireTime)
}

/**
 * 检查是否已登录
 */
export function isLoggedIn(): boolean {
  const token = getToken()
  return !!token && !isTokenExpired()
}

/**
 * 格式化token（添加Bearer前缀）
 */
export function formatToken(token: string): string {
  return token.startsWith('Bearer ') ? token : `Bearer ${token}`
}

/**
 * 从完整token中提取纯token值
 */
export function extractToken(fullToken: string): string {
  return fullToken.replace('Bearer ', '')
}